// 碳减排方案、减排方法学展示
import React, { Children, useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import './reductionOptions.less';
import { Table, Select, Button, Input } from 'antd';
import 'antd/dist/antd.css';
const { Option } = Select;
import { getDictionariesList, getReductionList, downloadReductionTemplate } from '@/services/carbon'

const reductionOptions = (props) => {
  // 是否显示碳资产申请弹出框
  const [isVisible, setIsVisible] = useState(false);
  // 表格总数据
  const [dataSource, setDataSource] = useState([]);
  // 分页数据
  const [pagination, setPagination] = useState({
    pageNum: 1,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 企业筛选值
  const [itemName, setItemName] = useState('');
  // 预计减排量筛选项
  const [reductionFilter, setReductionFilter] = useState([]);
  // 预计减排量筛选值
  const [emissionReductionNum, setEmissionReductionNum] = useState('');
  // 方法学筛选值
  const [methodology, setMethodology] = useState('');
  // 表格自适应高度
  const [scrollY, setScrollY] = useState(0);
  // 下载防重复
  const [downloadStatus, setDownloadStatus] = useState(false);
  const containerRef = useRef(null);
  // 表格自适应高度钩子
  useEffect(() => {
    const handleResize = () => {
      if (containerRef.current) {
        const containerHeight = containerRef.current.clientHeight;
        setScrollY(containerHeight - 100); // 100 是你想减去的像素值
      }
    };
    handleResize(); // 初始化时计算高度
    window.addEventListener('resize', handleResize); // 添加 resize 事件监听
    return () => {
      window.removeEventListener('resize', handleResize); // 清理事件监听
    };
  }, []);

  useEffect(() => {
    // 调用预计碳减排筛选项接口
    fetchReductionFilterData()
    // 调用表格数据接口
    fetchReductionList()
  }, [])

  // 监听当前页发生改变，查询表格数据
  useEffect(() => {
    fetchReductionList();
  }, [pagination.pageNum])

  // 碳资产申请交易所遍历数组
  const applyList = [
    { name: '北京绿色交易所', address: 'https://www.cbeex.com.cn/' },
    { name: '上海环境能源交易所', address: 'https://www.cneeex.com/' },
    { name: '广州碳排放权交易所', address: 'https://www.cnemission.com/' },
    { name: '深圳排放权交易所', address: 'https://szets.com/index.html' },
    { name: '天津排放权交易所', address: 'https://www.chinatcx.com.cn/' },
    { name: '湖北碳排放权交易中心', address: 'https://www.hbets.cn/' },
    { name: '海峡环境能源交易中心', address: 'https://carbon.hxee.com.cn/' },
    { name: '重庆碳排放权交易中心', address: 'https://tpf.cqggzy.com/' },
  ]

  // 表格列配置
  const columns = [
    { title: '项目名称', dataIndex: 'itemName', key: 'itemName', width: '25%', align: 'center' },
    {
      title: '减排方案', dataIndex: 'reductionProgramme', key: 'reductionProgramme', width: "25%", align: 'center',
      render: (text, record) => (
        <div style={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={() => handleRowClick(record, 1)}>
          {text}
        </div>
      )
    },
    {
      title: '减排方法学', dataIndex: 'methodology', key: 'methodology', width: "25%", align: 'center',
      render: (text, record) => (
        <div style={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={() => handleRowClick(record, 2)}>
          {text}
        </div>
      )
    },
    { title: '预计减排量(吨CO2)', dataIndex: 'emissionReductionNum', key: 'emissionReductionNum', width: "15%", align: 'center' },
  ];

  // 获取预计减排量筛选项
  const fetchReductionFilterData = async () => {
    try {
      // 获取接口数据并赋值
      const res = await getDictionariesList({
        dictType: 'carbon_emission_reduction'
      })
      if (res.code === 200) {
        setReductionFilter(res.data)
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 下载模板接口
  const downloadTemplate = async (params, type) => {
    setDownloadStatus(true)
    try {
      // 获取接口数据并赋值
      const res = await downloadReductionTemplate({
        fileName: type === 1 ? params.itemName : params.methodology,
        type: type
      })
      let fileName = ''
      if (type === 1) {
        fileName = params.itemName
        // 减排方案中 * 是用 _ 表示 / 直接去掉
        const split = fileName.split(":")
        fileName = split[split.length - 1].replace(/\//g, "").replace(/\*/g, "_")
      } else if (type === 2) {
        fileName = params.methodology
        // 减排方法学中 / 直接去掉
        fileName = fileName.replace(/\//g, "")
      }
      const blob = new Blob([res], { type: 'application/pdf' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName // 设置下载文件的文件名
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      setDownloadStatus(false)
    } catch (error) {
      console.error(error)
    }
  };

  const handleRowClick = (record, type) => {
    if (downloadStatus) {
      return
    }
    // 调用下载模板事件
    downloadTemplate(record, type)
  };

  // 处理搜索按钮点击事件
  const handleSearch = (params) => {
    // 当前页为第一页时，不改变当前页直接直接调用接口，否则将当前页设置成第一页
    if (pagination.pageNum === 1) {
      fetchReductionList()
    } else {
      setPagination({ ...pagination, pageNum: 1, current: 1 });
    }
  };

  // 获取表格数据接口
  const fetchReductionList = async (params) => {
    try {
      // 拼接页数数据及筛选项数据，获取接口数据并赋值
      const res = await getReductionList({ ...pagination, itemName: itemName, methodology: methodology, emissionReductionNum: emissionReductionNum })
      if (res.code === 200) {
        setDataSource(res)
        setPagination({ ...pagination, total: res.total })
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 切换当前页，修改当前页的值，再触发监听钩子
  const handlePaginationChange = (page) => {
    setPagination({ ...pagination, pageNum: page, current: page });
  };

  // 点击碳资产申请按钮，触发显示隐藏弹出框
  const showApplyList = () => {
    setIsVisible(!isVisible);
  }

  return (
    <div className="reductionOptions-content">
      <div className="top-box">
        <div className="filter-container">
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">企业查找:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查找的企业简称"
                value={itemName}
                onChange={e => setItemName(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <span className="filter-name">预计减排量筛选:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的企业减排量筛选"
                onChange={value => setEmissionReductionNum(value)}
                allowClear
              >
                {reductionFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">方法学查找:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查找的企业简称"
                value={methodology}
                onChange={e => setMethodology(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <Button type="primary" onClick={handleSearch} className="searchBtn">
                搜索
              </Button>
              <Button type="primary" onClick={showApplyList} className="applyBtn">
                碳资产开发申请
              </Button>
              {isVisible && (
                <div className='applyList'>
                  {applyList.map((item, index) => (
                    <div className='content-box' key={index}>
                      <div className='name'>{item.name}</div>
                      <div className='address'>{item.address}</div>
                    </div>
                  ))
                  }
                </div>
              )}
            </div>
          </div>
        </div>

      </div>
      <div className="center-box">
        <div className="table-container" ref={containerRef}>
          <Table
            dataSource={dataSource.rows}
            columns={columns}
            pagination={{
              ...pagination,
              showSizeChanger: false,
              pageSizeOptions: [],
              onChange: handlePaginationChange,
            }}
            scroll={{ y: scrollY }}
          />
        </div>
      </div>
    </div>
  )
};

export default connect()(reductionOptions);
